package com.everyday;

public class Solution1053 {
    public int[] prevPermOpt1(int[] arr) {
        int index = arr.length - 1;
        while (index != 0) {
            if (arr[index] >= arr[index - 1]) {
                index--;
            } else {
                int j = index;
                index--;
                int max = arr[j];
                for (int i = j + 1; i < arr.length; i++) {
                    if (arr[i] < arr[index]) if (arr[i] > arr[j]) j = i;
                }
                int tmp = arr[index];
                arr[index] = arr[j];
                arr[j] = tmp;
                break;
            }
        }
        return arr;
    }
}
